<?php
/**
 * 分类模型
 * 
 * @version $Id: Classes.php 659 2013-01-23 14:24:07Z linsir123 $
 */
class modelClasses 
{
	/**
	 * @var 模型
	 */
	public $dbClass;
	
	/**
	 * @var 缓存
	 */
	public $cache;
	
	/**
	 * @var 数据统计
	 */
	public $statistics;
	
	/**
	 * 构造函数
	 */
	public function __construct()
	{
		App::V('pinyin');
		///
		$this->dbClass = D::classes();
	}
	
	/**
	 * 析构函数
	 */
	public function __destruct()
	{
		// App::log($this->statistics, "modelClasses");
	}
	
	/**
	 * [取一个分类] 
	 * // 根据父ID和拼音码
	 */
	public function getByPidPinyin($parentId, $pinyin)
	{
		$this->_statistics("getByPidPinyin");
		
		///
		$row = $this->dbClass->where(array(
				'parent_id' => $parentId, 
				'pinyin' => $pinyin, 
			))->getRow();
			
		///
		$this->_writeCache(array($row));
		
		///
		return empty($row) ? array() : array(
			$row['class_id'],
			$row['pinyin'],
		);
	}
	
	/**
	 * 
	 */
	public function get($classId, $format = true)
	{
		$this->_statistics("get");
		
		///
		$row = isset($this->cache[$classId]) ? $this->cache[$classId] : array();
		
		///
		if (empty($row)) {
			$row = $this->dbClass->where(array(
					'class_id' => $classId, 
				))->getRow();
				
			///
			$this->_writeCache(array($row));
		}
		
		///
		return $format ? $this->_format($row) : $row;
	}
	
	/**
	 * 
	 */
	public function getSub($classId, $format = true)
	{
		$this->_statistics("getSub");
		
		///
		$rows = $this->dbClass->where(array(
				'parent_id' => $classId, 
			))->getResults();
			
		///
		$this->_writeCache($rows);
		
		///
		if ($format) {
			$tmp = array();
			foreach ($rows as $v) 
				$tmp[] = $this->_format($v);
				
			return $tmp;
		}
		
		///
		return $rows;
	}
	
	/**
	 * 
	 */
	public function getShop()
	{
		$list = M::topRequest()->shopcatsListGet();
		///
		return $list;
	}
	
	
	/// 以下为私有方法 ///
	
	
	/**
	 * 
	 */
	private function _writeCache($rows)
	{
		if (is_array($rows)) {
			foreach ($rows as $v) 
				$this->cache[$v['class_id']] = $v;
		}
	}
	
	/**
	 * 
	 */
	private function _format($row)
	{
		$foramt = array(
			'id' => 'class_id',
			'pid' => 'parent_id',
			'title' => 'title',
			'pinyin' => 'pinyin',
		);
		
		///
		$data = array();
		if ( ! empty($row)) {
			foreach ($foramt as $k => $v) 
				$data[$k] = $row[$v];
		}
		
		return $data;
	}
	
	/**
	 * API调用统计
	 */
	private function _statistics($api)
	{
		if (isset($this->statistics[$api])) 
			$this->statistics[$api]++;
		else 
			$this->statistics[$api] = 1; 
	}
}
